import rclpy
from rclpy.node import Node
from std_msgs.msg import String
import psutil
import json

class SystemInfoPublisher(Node):
    def __init__(self):
        super().__init__('system_info_publisher')
        self.publisher_ = self.create_publisher(String, '/system_info', 10)
        self.timer = self.create_timer(1.0, self.publish_system_info)
    
    def publish_system_info(self):
        # 获取每个CPU核心的占用率
        cpu_usage = psutil.cpu_percent(interval=0, percpu=True)
        memory_info = psutil.virtual_memory()

        # 计算CPU平均使用率
        cpu_avg = sum(cpu_usage)/len(cpu_usage)  # 新增计算逻辑

        # 构建JSON格式的数据
        system_info = {
            "cpu_usage": cpu_usage,
            "cpu_avg": cpu_avg,  # 新增字段
            "memory_usage": memory_info.percent
        }
        
        # 将数据转为JSON字符串
        system_info_json = json.dumps(system_info)
        
        # 创建消息并发布
        system_info_msg = String()
        system_info_msg.data = system_info_json
        
        self.publisher_.publish(system_info_msg)
        # self.get_logger().info(f"Published system info: {system_info_msg.data}")

def main(args=None):
    rclpy.init(args=args)
    system_info_publisher = SystemInfoPublisher()
    rclpy.spin(system_info_publisher)
    
    system_info_publisher.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()
